from django.http import StreamingHttpResponse, HttpResponse
from rest_framework.views import APIView
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response  # 新增：导入Response用于错误返回
from .services import CozeFinanceService
from .serializers import ResumeChatSerializer

#
# from rest_framework.renderers import JSONRenderer, BaseRenderer
#
# class PlainTextRenderer(BaseRenderer):
#     media_type = 'text/plain'
#     format = 'txt'
#
#
# class FinanceChatView(APIView):
#     """财务助手流式聊天接口"""
#     renderer_classes = [PlainTextRenderer]  # ← 关键行
#     def __init__(self, **kwargs):
#         super().__init__(** kwargs)
#         self.coze_service = CozeResumeService()
#
#     def post(self, request):
#         try:  # 新增：全局异常捕获
#             # 1. 验证请求数据
#             serializer = ResumeChatSerializer(data=request.data)
#             if not serializer.is_valid():
#                 # 验证失败：返回400错误响应
#                 return Response(serializer.errors, status=400)
#
#             prompt = serializer.validated_data["prompt"]
#             user_id = serializer.validated_data["user_id"]
#
#             # 2. 定义流式生成器
#             def stream_generator():
#                 try:
#                     yield from self.coze_service.stream_chat(prompt, user_id)
#                 except Exception as e:
#                     yield f"[ERROR]{str(e)}"
#
#             # 3. 返回流式响应（正常路径）
#             return StreamingHttpResponse(
#                 stream_generator(),
#                 content_type="text/plain; charset=utf-8"
#             )
#
#         except Exception as e:  # 捕获所有未预期的异常
#             # 确保即使出错也返回响应，而非None
#             return Response(
#                 {"error": f"服务器内部错误：{str(e)}"},
#                 status=500
#             )



from django.http import StreamingHttpResponse
from rest_framework.views import APIView
from rest_framework.exceptions import ValidationError
# 修改为
from .services import CozeFinanceService
from .serializers import ResumeChatSerializer


class FinanceChatView(APIView):
    """财务助手流式聊天接口（强制返回 text/plain）"""

    def __init__(self, **kwargs):
        super().__init__(** kwargs)
        self.coze_service = CozeFinanceService()

    def post(self, request):
        try:
            # 1. 验证请求数据
            serializer = ResumeChatSerializer(data=request.data)
            if not serializer.is_valid():
                # 验证失败时，也返回 text/plain 格式（避免 406）
                response = HttpResponse(
                    f"参数错误：{serializer.errors}",
                    content_type="text/plain; charset=utf-8",
                    status=400
                )
                return response

            prompt = serializer.validated_data["prompt"]
            user_id = serializer.validated_data["user_id"]

            # 2. 定义流式生成器
            def stream_generator():
                try:
                    yield from self.coze_service.stream_chat(prompt, user_id)
                    yield "[DONE]"
                except Exception as e:
                    yield f"[ERROR]{str(e)}"

            # 3. 关键：强制设置 Content-Type 为 text/plain，禁用框架格式转换
            response = StreamingHttpResponse(
                stream_generator(),
                content_type="text/plain; charset=utf-8"  # 明确文本流格式
            )
            # 禁止 DRF 自动转换响应格式（重要！）
            response["X-Content-Type-Options"] = "nosniff"
            return response

        except Exception as e:
            # 异常时也返回 text/plain 格式
            return HttpResponse(
                f"服务器错误：{str(e)}",
                content_type="text/plain; charset=utf-8",
                status=500
            )


from rest_framework.permissions import AllowAny
from .models import FinanceChatHistory
from rest_framework.pagination import PageNumberPagination
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response


class StandardResultsSetPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'page_size'
    max_page_size = 100


@api_view(['GET'])
@permission_classes([AllowAny])  # 实际项目中建议使用更严格的权限控制
def get_chat_history(request):
    """获取用户聊天历史记录"""
    user_id = request.query_params.get('user_id')
    if not user_id:
        return Response({"error": "user_id不能为空"}, status=400)

    history = FinanceChatHistory.objects.filter(user_id=user_id)
    paginator = StandardResultsSetPagination()
    result_page = paginator.paginate_queryset(history, request)

    data = [
        {
            "id": str(item.id),
            "prompt": item.prompt,
            "ai_response": item.ai_response,
            "created_at": item.created_at.strftime('%Y-%m-%d %H:%M:%S')
        } for item in result_page
    ]

    return paginator.get_paginated_response(data)